package com.lgl.scs.system.service;

import com.lgl.scsapi.base.dao.DaoSupport;
import com.lgl.scsapi.system.model.PageData;
import com.lgl.scsapi.util.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.PoolException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service("dictionariesService")
public class DictionariesService{
	private Logger log = LoggerFactory.getLogger(DictionariesService.class);
	@Resource(name = "daoSupport")
	private DaoSupport dao;
    @Resource
    private RedisTemplate redisTemplate;

	//新增
	public void save(PageData pd){
		dao.save("DictionariesMapper.save", pd);
	}
	
	//修改
	public void edit(PageData pd){
		dao.update("DictionariesMapper.edit", pd);
	}
	
	//通过id获取数据
	public PageData findById(PageData pd) {
		return (PageData) dao.findForObject("DictionariesMapper.findById", pd);
	}
	
	//查询总数
	public PageData findCount(PageData pd) {
		return (PageData) dao.findForObject("DictionariesMapper.findCount", pd);
	}

	/**
	 * 查询数据字典的名称和编码
	 * @param pageData
	 * @return
	 */
	public List<PageData> listDictionaries(PageData pageData) {
		if (pageData == null || pageData.isEmpty()){
			return null;
		}
		String parentId = pageData.getString("parentId"),
				dicMapper = "DictionariesMapper.listDictionaries";
		//如果redis不可用
        if (!StringUtils.hasText(parentId) || !Constants.REDIS_IS_USABLE) {
			return (List<PageData>) dao.findForList(dicMapper, pageData);
		}
		String redisKey = Constants.DICT_PARENT_ID + parentId;
		List<PageData> dictList = null;
		try{
            dictList = redisTemplate.opsForList().range(redisKey, 0, 100);
			if (dictList == null || dictList.isEmpty()) {
				dictList = (List<PageData>)dao.findForList(dicMapper, pageData);
                redisTemplate.opsForList().rightPushAll(redisKey, dictList);
			}
		}catch (Exception e) {
			log.error(e.toString(),e);
			if (e instanceof PoolException){
				dictList = (List<PageData>)dao.findForList(dicMapper, pageData);
                Constants.REDIS_IS_USABLE = false;
			}
		}
		return dictList;
	}

}